package com.example.disinfestation.controller;


import com.alibaba.fastjson.JSONObject;
import com.example.disinfestation.entity.Order;
import com.example.disinfestation.entity.WxUser;
import com.example.disinfestation.mapper.OrderMapper;
import com.example.disinfestation.service.WxUserService;
import com.example.disinfestation.util.AESUtil;
import com.example.disinfestation.util.JsonResult;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.example.disinfestation.WXPay.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;


@Controller
public class WxUserController  extends  BaseController{

    @Autowired
    WxUserService wxUserService;
    @Autowired
    OrderMapper orderMapper;


    @RequestMapping("hello")
    @ResponseBody
    public String hello(HttpServletResponse response) throws Exception {

        Map<String, Object> notifyMap = new HashMap<>();
        notifyMap.put("req_info","6j0ML/J38E75LRrvJnkz08ObR5g3ygFEd8pEO74nuB0kzstqE8rX69dXkRkZKg7up7d5ToxNX93GTF69KUbxDaqfLPOmL+tcljOIZuFmbe3TfaXJ3k7NrBa30wTJXwuvjXb3NguZi4D1tVCAuvWsCnt3X3mukPbv09EQbnNP+Ok8WAgipt5HSMoGGWAIUQQLTLr+Z01W4USvm+pi79Qy3EQzSXnPofR6Fa7Re5cdd5bnKRudDq8dmzWl8CRdjTCI8j2koph2IlHmEcYTs+ksWac7fimTnpHWjwkaqpDBFhiXMUHKM7iWW4vKxMd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6hI/Pw9naNA9QjeiEyg9aiaYchOSzhznoQAaN6TX5hNcl3T4aNu0rBKIW1LKNct6yWtYwywqc19aHbueC/t50u9IRIGH6CjW2HvWzTUC0rxO3mxL5P5STfcIpX+TjOP2oCHBX6DoGNVa5SheYn/xeOW+AX47KX7SnsjNo8DN0uH6Uk7jXwtiqiQZgKAQjUVGJGsMOFhcZ/USLqlNsKa6gxzuxwgYn3OX2GzCkIqczB1CUYbEDIIjhxOWHqIzzlvlpVhi6YuyMmgbJxrKbrM8bNOUdykylIQK6Om1AB/ZBfTuce/MqtYwDmZaqnQlKIc4pClf8RKyUpuiWKB1QivdJ1bHWI/SijuQKYROGdLtX750GSjYnpdFelxe0yPHpuftTdcyEjOa6MufrNIMsmfnCTF0U8evuy5UKtSNaXLiQnz8OLvLi7U8HYkpp/je62drpRqsEtr3pjormXtytHp6SqIHKXdy+BM4tGmaAff4//OXogY1t2qyw/hCWlot8vhKJUZQeG8jaFCjt66XGvvGWZn/fW+YZzwN1Bo6pYvWXmi8/ydd6T0o4kk3hsbjxe9I1cqLwAYUrt2CGvnRH7QsHUHMd7WeXwLSqEhaaBai5oKwCsZEUyggSNS9tJGiJrxcaeH0e2LVip2qWY9uto8Esbtvt5ttZTv6c1WEUL8bEwS4m9z80o1W61GPM9EQONvv8Mmp8KVTurqQBUwg5AYjXrd+ljFUlWSsUxXSA/n7mlE=";//得到信息进行解密
        String req_info = notifyMap.get("req_info").toString();//得到信息进行解密
        System.out.println(req_info);
        System.err.println(AESUtil.decryptData(req_info));

        return "null";

    }





    /**
     * 微信授权时录入用户数据
     */
    @RequestMapping(value = "wxLogin")
    @ResponseBody
    @Transactional
    public Map<String,Object> insert(@RequestParam("code")String code, HttpSession session) throws ClientProtocolException, IOException {
        //返回map
        System.err.println("微信授权登录");
        System.err.println("code值： "+code);
        Map<String,Object> resultMap = new HashMap<>();
        String appid = WXPayConstants.APP_ID;
        String secret = WXPayConstants.SECRET;

        String loginUrl="https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+secret+"&js_code="+code+"&grant_type=authorization_code";
        try {
            CloseableHttpClient client = null;
            CloseableHttpResponse response = null;
            try {
                // 创建http GET请求
                HttpGet httpGet = new HttpGet(loginUrl);
                client = HttpClients.createDefault();
                // 执行请求
                response = client.execute(httpGet);
                HttpEntity entity = response.getEntity();//得到返回数据

                String result = EntityUtils.toString(entity);
                System.err.println("微信返回的结果"+result);

                resultMap.put("data", result);//进行封装
                System.err.println(resultMap);

                JSONObject json_test = JSONObject.parseObject(result);
                String wxOpenid = json_test.getString("openid");
                String sessionKey = json_test.getString("session_key");
                System.err.println("openid值: "+wxOpenid);//得到微信openID
                System.err.println("sessionKey值: "+sessionKey);
                WxUser user = wxUserService.selectByid(wxOpenid);//根据id数据库数据查询

                System.err.println("用户信息: "+user);

                if (user == null){//如果user等于null说明该用户第一次登录，数据库没有该用户信息。
                    resultMap.put("state", 2000);
                    resultMap.put("data", wxOpenid);
                    resultMap.put("sessionKey", sessionKey);
                    resultMap.put("message", "未查询到用户信息");
                }else {
                    resultMap.put("state", 2000);
                    resultMap.put("data", wxOpenid);//查找的用户信息进行封装返回
                    resultMap.put("sessionKey", sessionKey);
                    resultMap.put("user", user);//查找的用户信息进行封装返回
                    resultMap.put("message", "该用户已存在");
                    return resultMap;
                }
                if(StringUtils.isEmpty(wxOpenid)){
                    resultMap.put("state", 2000);
                    resultMap.put("message", "未获取到openid");
                    return resultMap;
                }
            } finally {
                if (response != null) {
                    response.close();
                }
                if (client != null) {
                    client.close();
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultMap;
    }


    /*保存微信用户信息*/
    @RequestMapping("/insertWxUser")
    @ResponseBody
    public JsonResult<WxUser> insertUser(WxUser user){
        JsonResult result = new JsonResult();
        System.out.println("微信用户信息保存");


        String username = user.getUsername();
        String avatar = user.getAvatar();
        String wxOpenid = user.getOpenid();

        System.out.println("用户名: "+username);
        System.out.println("头像: "+avatar);
        System.out.println("openid: "+wxOpenid);
        try {

            WxUser user1 = wxUserService.selectByid(wxOpenid);//根据id数据库数据查询

            if (user1==null) {
                wxUserService.insertWxUser(username, avatar, wxOpenid);
                result.setState(SUCCESS);
            }
            else {
                wxUserService.updateWxUser(username, avatar, wxOpenid);
                result.setState(SUCCESS);
            }
        }catch (Exception e){
            result.setMessage("保存用户信息失败，请重新尝试");
        }
        return result;
    }









}
